package com.guldan.jaina.manager;

import com.guldan.core.exception.BusinessException;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.area.AreaDTO;
import com.guldan.jaina.dto.area.AreaSearchDTO;
import com.guldan.jaina.dto.organization.OrganizationDTO;
import com.guldan.jaina.utils.AreaDomainConvertUtils;
import com.guldan.jaina.utils.UserUtils;
import com.guldan.mapper.db.entity.Area;
import com.guldan.mapper.db.entity.AreaExample;
import com.guldan.mapper.db.mapper.AreaMapperExt;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Silas.
 * Date: 2016/11/7
 * Time: 22:55
 */
@Service
public class AreaManager extends BaseManager {

    @Autowired
    private AreaMapperExt areaMapperExt;

    //获取单个区域信息
    public AreaDTO get(Integer areaId) {
        Area area = areaMapperExt.selectByPrimaryKey(areaId);
        if (area != null) {
            AreaDTO dto = AreaDomainConvertUtils.convert(area);
            if (area.getAreaParentId() != null && area.getAreaParentId() > 0) {
                Area parentArea = areaMapperExt.selectByPrimaryKey(area.getAreaParentId());
                if (parentArea != null)
                    dto.setAreaParentName(parentArea.getAreaName());
            }
            return dto;
        }
        return null;
    }


    //新增/更新单个区域，传入：AreaDTO
    public AreaDTO save(AreaDTO dto) throws BusinessException {

        Area entity;
        if (dto.getAreaId() != null && dto.getAreaId() > 0) {
            entity = areaMapperExt.selectByPrimaryKey(dto.getAreaId());
            entity.setAreaCode(dto.getAreaCode());
            entity.setAreaName(dto.getAreaName());
            entity.setAreaNameZw(dto.getAreaNameZw());
            entity.setAreaLevelCode(dto.getAreaLevelCode());
            entity.setAreaParentId(dto.getAreaParentId());
            entity.setAreaParentCode(dto.getAreaParentCode());
            entity.setAreaTypeCode(dto.getAreaTypeCode());
            entity.setAreaNum(dto.getAreaNum());
            entity.setZipCode(dto.getZipCode());
            entity.setRemark(dto.getRemark());

            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            areaMapperExt.updateByPrimaryKeySelective(entity);
        } else {

            //判断是否存存在
            if (checkExist(dto.getAreaCode())) {
                throw new BusinessException("区划Code已存在");
            }

            entity = new Area();
            entity.setAreaCode(dto.getAreaCode());
            entity.setAreaName(dto.getAreaName());
            entity.setAreaNameZw(dto.getAreaNameZw());
            entity.setAreaLevelCode(dto.getAreaLevelCode());
            entity.setAreaParentId(dto.getAreaParentId());
            entity.setAreaParentCode(dto.getAreaParentCode());
            entity.setAreaTypeCode(dto.getAreaTypeCode());
            entity.setAreaNum(dto.getAreaNum());
            entity.setZipCode(dto.getZipCode());
            entity.setRemark(dto.getRemark());

            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getModifier());
            entity.setCreateTime(DateUtil.getCurrentTime());
            areaMapperExt.insertSelective(entity);
        }
        dto = AreaDomainConvertUtils.convert(entity);
        return dto;
    }

    //判断某个区划是否已经存在
    public Boolean checkExist(String areaCode) {
        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();
        criteria.andAreaCodeEqualTo(areaCode);
        criteria.andIsDeleteEqualTo(false);
        int count = areaMapperExt.countByExample(example);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    //判断某个区划是否已经存在
    public AreaDTO checkExistReturnDTO(String areaCode) {
        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();
        criteria.andAreaCodeEqualTo(areaCode);
        criteria.andIsDeleteEqualTo(false);
        List<Area> list = areaMapperExt.selectByExample(example);
        if (list != null && list.size() > 0) {
            return AreaDomainConvertUtils.convert(list.get(0));
        } else {
            return null;
        }
    }


    //删除单个区域信息
    public Boolean delete(Integer areaId) {
        Area entity = areaMapperExt.selectByPrimaryKey(areaId);
        entity.setIsDelete(true);
        return areaMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //分页查询区域信息列表
    public Pagination<AreaDTO> list(AreaSearchDTO areaSearchDTO) {


        logger.debug("[UserUtils.getUser().getUserName()] " + UserUtils.getUser().getUserName());


        Pagination<AreaDTO> result = new Pagination<AreaDTO>(areaSearchDTO.getCurrentPage(), areaSearchDTO.getPerPage());
        AreaExample example = buildSearchExample(areaSearchDTO);
        int total = areaMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<AreaDTO> data = new ArrayList<AreaDTO>();
            List<Area> list = areaMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (Area entity : list) {
                AreaDTO dto = AreaDomainConvertUtils.convert(entity);
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    public List<AreaDTO> getChildrenAreaDTOs(Integer parentId, Boolean withChildren) {
        List<AreaDTO> list = new ArrayList<>();

        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();
        criteria.andAreaParentIdEqualTo(parentId);

        criteria.andIsDeleteEqualTo(false);
        List<Area> entityList = areaMapperExt.selectByExample(example);

        if (entityList != null && entityList.size() > 0) {
            for (Area entity : entityList) {
                AreaDTO dto = AreaDomainConvertUtils.convert(entity);

                list.add(dto);

                if (withChildren) {
                    List<AreaDTO> childs = getChildrenAreaDTOs(entity.getAreaId(), withChildren);
                    list.addAll(childs);
                }
            }
        }
        return list;
    }

    public List<Integer> getChildrenAreaIds(Integer parentId, Boolean withChildren) {
        List<AreaDTO> list = getChildrenAreaDTOs(parentId, withChildren);
        List<Integer> ids = list.stream().map(AreaDTO::getAreaId).collect(Collectors.toList());
        return ids;
    }


    public List<AreaDTO> all(AreaSearchDTO areaSearchDTO) {
        AreaExample example = buildSearchExample(areaSearchDTO);
        List<AreaDTO> data = new ArrayList<AreaDTO>();
        List<Area> list = areaMapperExt.selectByExample(example);
        for (Area entity : list) {
            AreaDTO dto = AreaDomainConvertUtils.convert(entity);
            data.add(dto);
        }
        return data;
    }

    //build查询Example
    private AreaExample buildSearchExample(AreaSearchDTO search) {
        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(search.getAreaCode())) {
            criteria.andAreaCodeEqualTo(search.getAreaCode());
        }
        if (StringUtils.isNotBlank(search.getAreaName())) {
            criteria.andAreaNameEqualTo(search.getAreaName());
        }
        if (search.getAreaId() != null && search.getAreaId() > 0) {
            criteria.andAreaIdEqualTo(search.getAreaId());
        }
        if (search.getAreaParentId() != null && search.getAreaParentId() >= 0) {
            criteria.andAreaParentIdEqualTo(search.getAreaParentId());
        }
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("area_id asc");
        }
        return example;
    }

    /**
     * 批量插入区域
     *
     * @param list
     * @return
     */
    public Boolean batchImport(List<AreaDTO> list) {
        if (list != null && list.size() > 0) {
            for (AreaDTO dto : list) {
                save(dto);
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public AreaDTO getByDivisionCode(String divisionCode) {
        AreaExample example = new AreaExample();
        AreaExample.Criteria criteria = example.createCriteria();
        criteria.andDivisionCodeEqualTo(divisionCode);
        criteria.andIsDeleteEqualTo(false);
        return AreaDomainConvertUtils.convert(areaMapperExt.selectByExample(example).get(0));
    }


}
